package com.abe.libquick.main;

import android.text.TextUtils;

import com.abe.libcore.utils.CommonUtils;
import com.abe.libquick.base.BaseActivity;
import com.abe.libquick.databinding.ActivityVideoPlayerBinding;
import com.abe.libquick.utils.ConstantMBLib;
import com.abe.libquick.utils.MediaDecoder;
import com.abe.libquick.utils.VideoShowHelper;
import com.abe.libquick.utils.quick.EmptyUtils;
import com.bumptech.glide.Glide;

import cn.jzvd.JZUtils;
import cn.jzvd.Jzvd;

public class VideoPlayerActivity extends BaseActivity<ActivityVideoPlayerBinding> {

    @Override
    protected ActivityVideoPlayerBinding getBinding() {
        return ActivityVideoPlayerBinding.inflate(getLayoutInflater());
    }

    String img;

    @Override
    protected void initContent() {
        if (EmptyUtils.isEmpty(bundle()) || !bundle().containsKey(VideoShowHelper.VIDEO_PATH)) {
            finish();
            return;
        }
        String path = bundle().getString(VideoShowHelper.VIDEO_PATH, "");
        if (TextUtils.isEmpty(path)) {
            finish();
            return;
        }
        img = bundle().getString(ConstantMBLib.IMG_PATH, "");
        if (TextUtils.isEmpty(img)) {
            boolean isNetVideo = path.contains("http");
            try {
                MediaDecoder.create()
                        .setType(isNetVideo ? MediaDecoder.TYPE_VIDEO_NET : MediaDecoder.TYPE_VIDEO_LOCAL)
                        .setDataSource(path)
                        .setListener(bitmap -> runOnUiThread(() -> {
                            binding.itemVideo.setUp(path, "");
                            binding.itemVideo.posterImageView.setImageBitmap(bitmap);
                            binding.itemVideo.startVideoAfterPreloading();
                        })).start(MediaDecoder.VIDEO_START);
            } catch (Exception e) {
                e.printStackTrace();
                CommonUtils.INSTANCE.log(e.getMessage());
                binding.itemVideo.setUp(path, "");
                binding.itemVideo.startVideoAfterPreloading();
            }
        } else {
            binding.itemVideo.setUp(path, "");
            Glide.with(this).load(img).into(binding.itemVideo.posterImageView);
            binding.itemVideo.startVideoAfterPreloading();
        }
        binding.itemClose.setOnClickListener(view -> onBackPressed());
    }

    @Override
    protected void onPause() {
        super.onPause();
        JZUtils.clearSavedProgress(this, null);
        Jzvd.releaseAllVideos();
    }

    @Override
    public void onBackPressed() {
        if (Jzvd.backPress()) {
            return;
        }
        super.onBackPressed();
    }
}